package com.txw.travel.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

//Security配置类
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)//开启鉴权注解
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //security配置类
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //自定义表单登录
        http.formLogin()
                .loginPage("/backstage/admin_login")//配置登录页面
                .usernameParameter("username") //用户名
                .passwordParameter("password") //密码
                .loginProcessingUrl("/backstage/admin/login")  //表单处理路径
                .successForwardUrl("/backstage/index")  //成功跳转
                .failureForwardUrl("/backstage/admin_fail"); //失败跳转

        //权限拦截配置
        http.authorizeRequests()
                .antMatchers("/backstage/admin/login").permitAll() //放行登录接口
                .antMatchers("/backstage/admin_login").permitAll() //放行登录界面
                .antMatchers("/backstage/admin_fail").permitAll()//放行登录失败
                .antMatchers("/**/*.css", "/**/*.js").permitAll()//放行静态资源
                .antMatchers("/backstage/**").authenticated(); //其他资源需要进行权限判断

        //退出登录配置
        http.logout()
                .logoutUrl("/backstage/admin/logout") //退出登录路径
                .logoutSuccessUrl("/backstage/admin_login") //退出登录跳转页面
                .clearAuthentication(true)  //清除认证信息
                .invalidateHttpSession(true); //清除session

        //异常处理器
        http.exceptionHandling()
                .accessDeniedHandler(new MyAccessDeniedHandler()); //权限不足异常处理

        //关闭csrf防护
        http.csrf().disable();

        //开启跨域访问
        http.cors();

        super.configure(http);
    }

    //密码加密器
    @Bean
    public BCryptPasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
}
